package gw.demo2.controller;

import gw.demo2.entity.User;
import gw.demo2.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public ResponseEntity<?> userLogin(@RequestBody Map<String, Object> request) {
        int userId = Integer.parseInt(request.get("userId").toString());
        String password = request.get("password").toString();

        User user = userService.login(userId, password);
        if (user != null) {
            return ResponseEntity.ok().body(user);
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid credentials");
        }
    }

    @PostMapping("/register")
    public ResponseEntity<?> userRegister(@RequestBody Map<String, Object> request) {
        String nickname = request.get("nickname").toString();
        String password = request.get("password").toString();

        boolean registered = userService.register(nickname, password);
        if (registered) {
            // 获取刚注册的用户ID
            int userId = userService.getUserIdByNickname(nickname);

            RegisterResponse response = new RegisterResponse();
            response.setSuccess(true);
            response.setMessage("User registered successfully");
            response.setId(userId);

            return ResponseEntity.ok().body(response);
        } else {
            return ResponseEntity.status(HttpStatus.CONFLICT).body("Nickname already exists");
        }
    }

    @PutMapping("/profile")
    public ResponseEntity<?> updateProfile(@RequestBody Map<String, Object> request) {
        int userId = Integer.parseInt(request.get("userId").toString());
        String newNickname = request.get("newNickname").toString();
        String newPassword = request.get("newPassword").toString();

        if (userService.updateUser(userId, newNickname, newPassword)) {
            return ResponseEntity.ok().body("Profile updated successfully");
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("User not found");
        }
    }

    @GetMapping("/purchase-records")
    public ResponseEntity<?> getPurchaseRecords(@RequestParam int userId) {
        return ResponseEntity.ok().body(userService.getPurchaseRecordsByUserId(userId));
    }
}